package OliveMiscUtil;

# Copyright (c) 2005, Shawn Boyette
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# * Redistributions of source code must retain the above copyright
#   notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
#   notice, this list of conditions and the following disclaimer in
#   the documentation and/or other materials provided with the
#   distribution.
#  * Neither the name of the Olive Newsreader  nor the names of its
#    contributors may be used to endorse or promote products derived
#    from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.

require Exporter;
use warnings;
use strict;

our @ISA       = qw(Exporter);
our @EXPORT    = qw( &sysinit &sysinit2 &setpollwait &followlink &quitit &helppop &aboutpop );

sub sysinit {
    my $cui     = shift;
    my $dotdir  = $ENV{HOME} . "/.olive";
    my $feeddir = $ENV{HOME} . "/.olive/feeds";
    my $dotfile = $dotdir . "/olive.yaml";

    # say hello if we're new
    $cui->dialog( -bfg => 'blue',
                  -message => "          This is Olive\n    A Totally Sweet Newsfeeder\n\nPress 'h' or '?' anytime for help.")
        unless (-e $dotdir);

    # set up dotdirm feeddir, and dotfile
    mkdir $dotdir,  0700 unless (-e $dotdir);
    mkdir $feeddir, 0755 unless (-e $feeddir);
    system("touch $dotfile") unless (-e $dotfile);
}

#-------------------------------------------------------------

sub sysinit2 {
    my $cui = shift;
    my $dbh = $cui->userdata->{dbh};

    # set up story database if this is the first run
    unless ($cui->userdata->{c}->{fr}) {
        my $statement = "CREATE TABLE stories (id INTEGER PRIMARY KEY, nick TEXT, timestamp INT, md5 TEXT, read INT, new INT, link TEXT, title TEXT, desc TEXT)";
        my $sth = $dbh->prepare($statement);
        $sth->execute;
        $cui->userdata->{c}->{fr} = 1;
        $cui->userdata->{c}->write;
    } else {
        # clean shit up, y0
        my $statement = "VACUUM";
        my $sth = $dbh->prepare($statement);
        $sth->execute;
    }
}

#-------------------------------------------------------------

sub errorbox {
    my ($cui,$msg) = @_;
    if($cui->getobj('dialog')){
        $cui->getobj('dialog')->focus;
        $cui->getobj('dialog')->draw;
        return;
    }
    $cui->dialog( -title => "Error", -message => $msg);
}

#-------------------------------------------------------------

sub followlink {
    my ($cui,$root) = @_;
    return unless $cui->userdata->{c}->{www};

    my $d   = $cui->userdata->{dbh};
    my $w   = $cui->userdata->{wins};
    my $cmd = $cui->userdata->{c}->{www};

    my $id = $w->{news}{list}->get;
    my ($link) = $d->selectrow_array("SELECT link FROM stories WHERE id = $id");

    $cmd =~ s/LINK/$link/;

    system($cmd);
}


#-------------------------------------------------------------

sub setpollwait {
    my $cui = shift;
    my $c = $cui->userdata->{c};
    $c->{pw} = 5 unless ($c->{pw});
    my $pw = $c->{pw} * 60;

    $cui->disable_timer('clock');
    $cui->set_timer('clock', sub { &OliveFeed::feedpoll($cui) }, $pw);
    $cui->enable_timer('clock');
}

#-------------------------------------------------------------

sub quitit {
    my $cui = shift;
    my $c = $cui->userdata->{c};
    
    if ($c->{coe}) {
    my $return = $cui->dialog( -message => "Really quit?",
                               -bfg     => "blue", 
                               -buttons => ['yes', 'no'],
                               
        );
        exit(0) if $return;
    } else {
        exit(0);
    }
}

#-------------------------------------------------------------

sub aboutpop {
    my $cui = shift;
    return if($cui->getobj('dialog'));
    my $about = <<ABOUT;
   ,ad8888ba,   88 88 
  d8"'    `"8b  88 ""
 d8'        `8b 88 
 88          88 88 88 8b       d8  ,adPPYba,
 88          88 88 88 `8b     d8' a8P_____88
 Y8,        ,8P 88 88  `8b   d8'  8PP"""""""
  Y8a.    .a8P  88 88   `8b,d8'   "8b,   ,aa
   `"Y8888Y"'   88 88     "8"      `"Ybbd8"`
  
                     A Curses::UI Newsfeeder

               Made possible by a grant from
                     The Tildedot Foundation
ABOUT

    $cui->dialog( -message => $about,
                  -title   => "About...",
                  -bfg     => 'blue',
    );
    $cui->enable_timer('clock');
}

#-------------------------------------------------------------

sub helppop {
    my $cui = shift;
    if($cui->getobj('help')) {
        $cui->getobj('help')->focus;
        $cui->getobj('help')->draw;
        return;
    }

    my $helpmsg = <<HELP;
GLOBAL KEYS ---------------------------------
 [  Previous story       ]  Next story
 m  Mark all read        M  Mark all unread
 r  Refresh news list    R  Force-refresh
 l  Pass link to browser w  Switch focus

 C-a Add an item to feed list 
 C-o Set options
 C-e Edit feed properties [BROKEN]
 C-r Remove items from feed list

 Q    Quit
 h,?  Show this message  
 C-t  Show About box

STORY LIST KEYS -----------------------------
 Up,Dn  Move story selector
 ENTER  Read story

STORY VIEW KEYS -----------------------------
 Up,k      Scroll text one line up
 Dn,j      Scroll text one line down
 PgUp,-    Scroll text one screen up
 PgDn,SPC  Scroll text one screen down
HELP
1;

    my $help = $cui->add('help', 'Window',
                         -border   => 1,
                         -bfg      => 'blue',
                         -title    => 'Help',
                         -height   => 20,
                         -width    => 52,
                         -centered => 1,
        );
    $help->{txt} = $help->add('htxt', 'TextViewer',
                              -text       => $helpmsg,
                              -border     => 1,
                              -height     => 14,
                              -width      => 48,
                              -vscrollbar => 1,
                              -x          => 1,
                              -y          => 1,
        );
    $help->{hkb} = $help->add('hbok', 'Buttonbox',
                              -y       => -2,
                              -x       => 43,
                              -buttons => [ { -label   => '< OK >',
                                              -value   => 1,
                                              -onpress => sub { $help->loose_focus;
                                                                $cui->delete('help');
                                                                $cui->enable_timer('clock');
                                                                $cui->draw },
                                            } 
                              ],
        );
    $help->draw;
    $help->focus;
}


1;
